package com.xiaoyu.lanling.wxapi;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;

import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.xiaoyu.base.AppConfig;
import com.xiaoyu.lanling.activity.base.AppCompatToolbarActivity;
import com.xiaoyu.lanling.event.login.WeChatAuthEvent;

import in.srain.cube.util.CLog;
import in.srain.cube.util.UTUtil;

public class WXEntryActivity extends AppCompatToolbarActivity implements IWXAPIEventHandler {

    private IWXAPI mIWXAPI;

    @Override
    protected void onCreateSafelyAfterAppFinishInit(Bundle savedInstanceState) {
        super.onCreateSafelyAfterAppFinishInit(savedInstanceState);
        mIWXAPI = WXAPIFactory.createWXAPI(this, AppConfig.wechatAppId(), true);
        mIWXAPI.registerApp(AppConfig.wechatAppId());
        handleIntent();
    }

    @Override
    protected void onResumeSafelyAfterAppFinishInit(boolean isFirstTimeResume) {
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        handleIntent();
    }

    @Override
    protected boolean isSetRequestedOrientationPortrait() {
        return Build.VERSION.SDK_INT != Build.VERSION_CODES.O;
    }

    @Override
    public void onReq(BaseReq baseReq) {
    }

    @Override
    public void onResp(BaseResp baseResp) {
        if (baseResp.getType() == ConstantsAPI.COMMAND_SENDAUTH) { // sdk login
            boolean isSuccess = baseResp.errCode == BaseResp.ErrCode.ERR_OK;
            String code = ((SendAuth.Resp) baseResp).code;

            new WeChatAuthEvent(isSuccess, code).post();

            Bundle params = new Bundle();
            params.putString("result2", isSuccess ? "success" : "fail");
            UTUtil.getInstance().logEvent("wechat_login_back_app", params);
        } else if (baseResp.getType() == ConstantsAPI.COMMAND_SENDMESSAGE_TO_WX) { // share
            boolean isSuccess = baseResp.errCode == BaseResp.ErrCode.ERR_OK;
//            new ShareEvent(isSuccess).post();
        }
        finish();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    private void handleIntent() {
        boolean result = mIWXAPI.handleIntent(getIntent(), this);
        if (!result) {
            finish();
        }
    }
}
